#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <queue>

using namespace std;

template<class T>
class BlockQueue
{
    static const int defaultnum = 20;
public:
    BlockQueue(int cap = defaultnum)
    : _maxcap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&p_cond, nullptr);
        pthread_cond_init(&c_cond, nullptr);
        low_water = _maxcap / 3;
        high_water = (_maxcap * 2) / 3;
    }

    // 生产
    void push(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        if(_q.size() == _maxcap)
        {
            // 队列满了，生产条件不满足，让生产者去休眠
            pthread_cond_wait(&p_cond, &_mutex);
        }
        // 1.满足生产条件 2.被唤醒
        
        _q.push(in);
        // 当队列中的任务数量超过高水位则唤醒消费者
        /*if(_q.size() > high_water)*/ pthread_cond_signal(&c_cond);

        pthread_mutex_unlock(&_mutex);
    }

    // 消费
    T pop()
    {
        pthread_mutex_lock(&_mutex);
        if(_q.size() == 0)
        {
            // 队列中没有任务，消费条件不满足，让消费者去休眠
            pthread_cond_wait(&c_cond, &_mutex);
        }
        
        T out = _q.front();
        _q.pop();
        /*if(_q.size() < low_water)*/ pthread_cond_signal(&p_cond);

        pthread_mutex_unlock(&_mutex);
        return out;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&p_cond);
        pthread_cond_destroy(&c_cond);
    }
private:
    queue<T> _q;
    int _maxcap;
    pthread_mutex_t _mutex;
    pthread_cond_t p_cond;
    pthread_cond_t c_cond;

    int low_water;
    int high_water;
};